package com.domino.client.view.board;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.domino.client.view.BoardGamePanel;
import com.domino.shared.model.Board;
import com.domino.shared.model.Brick;
import com.domino.shared.model.Color;
import com.domino.shared.model.Point;
import com.domino.shared.model.SimpleBoard;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;

public class BoardPanel extends FlowPanel {
	
	private Map<Point, BoardButton> modelViewMap = new HashMap<Point, BoardButton>();
	private int size;
	Color clientColor;
	
	public BoardPanel(BoardGameCallback panel, int size) {
		setStyleName("grid-othello");
		this.size = size;
		int buttonSize = (int)(38.0*7.0/size) ;
		String buttonPX = Integer.toString(buttonSize)+"px";
		String panelPX = Integer.toString(buttonSize*size)+"px";
		setSize(panelPX, panelPX); // remove?
		for(int y=0;y<size;y++) {
			for (int x=0;x<size;x++) {
				BoardButton button = createButton(panel, buttonPX,x,y);
				Point p = new Point(x,y);
				modelViewMap.put(p, button);
				add(button.getWidget());
				setPointEmpty(p);
			}
		}
		
	}
	
	public void setClientColor(Color color) {
		clientColor = color;
	}

	private void setPointEmpty(Point p) {
		BoardButton b = modelViewMap.get(p);
		b.setEmpty();
	}

	private BoardButton createButton(BoardGameCallback panel, String buttonPX, int x, int y) {
		BoardButton b = new BoardButton(panel, new Point(x,y), buttonPX);
		return b;
	}
	
	
	
	public void updateButtons(Board board, boolean displayAvailablePoints) {
		Set<Point> available = board.getAvailblePoints(clientColor);
		for (int x=0;x<size;x++) {
			for(int y=0;y<size;y++) {
				Point point = new Point(x, y);
				Color color=board.getColor(point);
				if (color!=null){
					setPointColor(point, color);
				} else if (displayAvailablePoints && available.contains(point)) {
					setPointAvailable(point);
				} else {
					setPointEmpty(point);
				}
			}
		}
		if (board.getBricks().size()>0) {
			markLastBricks(board.getBricks());
		}
	}
	
	private void markLastBricks(List<Brick> bricks) {
		Brick lastBrick = bricks.get(bricks.size()-1);
		setPointsLast(lastBrick);
		for(int i=bricks.size()-2;i>=0;i--) {
			Brick brick = bricks.get(i);
			if (lastBrick.getColor().equals(brick.getColor())==false) {
				return;
			}
			setPointsLast(brick);
		}
		
	}

	private void setPointsLast(Brick brick) {
		if (brick.getPoint()!=null) {
			BoardButton button = modelViewMap.get(brick.getPoint());
			button.setLastColor(brick.getColor());
		}
	}

	private void setPointAvailable(Point point) {
		BoardButton button = modelViewMap.get(point);
		button.setAvailable(clientColor);
	}
	
	private void setPointColor(Point point, Color color) {
		BoardButton button = modelViewMap.get(point);
		button.setColor(color);
	}

	
}
